<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title>角色管理</title>
<link rel="stylesheet" type="text/css" href="../../css/reset.css" />
<link rel="stylesheet" type="text/css" href="../../css/css.css" />
<link rel="stylesheet" type="text/css"
	href="../../js/jquery-easyui-1.4.3/themes/default/easyui.css" />
<link rel="stylesheet" type="text/css"
	href="../../js/jquery-easyui-1.4.3/themes/icon.css" />
<link rel="stylesheet" type="text/css" href="../../css/colorReset.css" />



<style type="text/css">
.table_role {
	width: 620px;
	margin: 0 auto;
}

.table_role p {
	padding: 0 0 5px 0;
}

.default_btn {
	margin: 0;
}

.select_role {
	width: 222px;
	height: 200px;
	border: 1px solid #d1d8de;
	overflow-y: scroll;
}

.select_role_title {
	width: 222px;
	height: 24px;
	line-height: 24px;
	vertical-align: middle;
	text-align: center;
	border: 1px solid #d1d8de;
	border-bottom: none;
	background: #f0fbff;
}

.select_role ul {
	margin: 0;
	width: 100%;
	overflow: hidden;
}

.select_role ul li {
	display: block;
	width: 100%;
	height: 25px;
	overflow: hidden;
	line-height: 25px;
	padding: 2px 0px;
	margin: 0;
	cursor: pointer;
}

.select_role ul li:nth-child(odd) {
	background-color: #f3f8fe;
}

.select_role ul li.active {
	background-color: #ffffc7;
}

.select_role ul li a {
	float: left;
	display: block;
	margin-left: 5px;
}

.select_role ul li img {
	float: left;
	display: block;
	margin-left: 10px;
	margin-top: 5px;
}

.select_role ul li a:hover {
	color: #000;
}

.popup_con {
	padding-bottom: 10px;
}

.move-btn {
	border: none;
	width: 81px;
	height: 29px;
	color: #fff;
	margin-bottom: 10px;
}

.move-to-right {
	background: url(../../images/move-to-right.png) center center no-repeat;
}

.move-to-left {
	background: url(../../images/move-to-left.png) center center no-repeat;
}
</style>

</head>

<body>

	<div class="main">
		<div class="data_con">
			<div id="toolbox" style="padding: 5px; height: 25px">
				<div style="margin-bottom: 5px; float: left">
					<a href="javascript:void(0)" onclick="onAdd()"
						class="easyui-linkbutton" id="toolbar_add" iconCls="icon-add"
						plain="true">新增</a> <a href="javascript:void(0)"
						onclick="update()" class="easyui-linkbutton" id="toolbar_modify"
						iconCls="icon-edit" plain="true">修改</a> <a
						href="javascript:void(0)" onclick="del()"
						class="easyui-linkbutton" id="toolbar_delete"
						iconCls="icon-remove" plain="true">刪除</a> <a
						href="javascript:void(0)" onclick="refresh()"
						class="easyui-linkbutton" id="toolbar_refresh"
						iconCls="icon-refresh" plain="true">刷新</a>
				</div>
			</div>
			<table id="datagrid" style="height: 300px"
				data-options="fitColumns:true,toolbar:'#toolbox'">
			</table>


		</div>

	</div>
	<div id="winEdit" class="easyui-window" title="用户管理-新增"
		style="width: 730px; height: auto;"
		data-options="iconCls:'icon-save',modal:true,minimizable:false,maximizable:false,collapsible:false">
		<form id="authorizeForm" method="post">
			<div class="popup_con">

				<ul>
					<li><label for="roleName" class="label">角色名字：</label>
						<div class="input_con">
							<input id="roleName" name="roleName"
								class="easyui-validatebox text"
								data-options="required:true,validType:'length[1,50]'"
								missingMessage="角色名字不能为空！" invalidMessage="输入值不能是非法字符！" />
						</div></li>
					<li><label for="remark" class="label">备注：</label>
						<div class="input_con">
							<input type="text" name="remark" id="remark"
								class="easyui-validatebox text"
								data-options="validType:'maxLength[100]'" />
						</div></li>
				</ul>

				<table cellpadding="0" cellspacing="0" class="table_role">
					<tr>
						<td style="width: 32%">
							<div class="select_role_title">可选权限</div>
							<div id="lopt" class="select_role">
								<ul>

								</ul>
							</div>
						</td>
						<td style="width: 21%" align="center"><input type="button"
							value="添加" id="lromve" class="move-btn move-to-right"> <br />
								<input type="button" value="添加全部" id="lromveall"
								class="move-btn move-to-right"> <br /> <input
									type="button" value="删除" id="romve"
									class="move-btn move-to-left"> <br /> <input
										type="button" value="删除全部" id="romveall"
										class="move-btn move-to-left"></td>
						<td style="width: 49%">
							<div class="select_role_title">已选权限</div>
							<div id="ropt" class="select_role">
								<ul>

								</ul>
							</div>
						</td>
					</tr>
				</table>
			</div>
		</form>

		<div id="buttons" class="button_con">
			<a href="javascript:void(0)" onclick="onSave()"
				class="easyui-linkbutton" id="instance_save" iconCls="icon-ok"
				plain="true">保存</a> <a href="javascript:void(0)" onclick="rePage()"
				class="easyui-linkbutton" id="cancalBtn" iconCls="icon-cancel"
				plain="true">取消</a>
		</div>
	</div>



	<script type="text/javascript" src="/webjars/json3/3.3.2/json3.min.js"></script>
	<script type="text/javascript"
		src="../../js/jquery-easyui-1.4.3/jquery.min.js"></script>
	<script type="text/javascript"
		src="../../js/jquery-easyui-1.4.3/jquery.easyui.min.js"></script>
	<script type="text/javascript"
		src="../../js/jquery-easyui-1.4.3/locale/easyui-lang-zh_CN.js"></script>

	<script type="text/javascript" src="../../js/cook/constants.js"></script>
	<script type="text/javascript" src="../../js/cook/FormValidate.js"></script>
	<script type="text/javascript" src="../../js/cook/public.js"></script>
	<script>
var modifyOrAddFlag;
var g_allPermissions = [];
//初始化数据
$(document).ready(function(){
		$('#winEdit').window('close');
		$(".button_con a" ).removeClass("l-btn-plain");
		
		
		
		$("#datagrid").datagrid({
			url : BASE_URL_ROLES + '?v=' + Date.parse(new Date()),
			method:'get',
			autoRowHeight:true,//自动行高
			nowrap:false,
			singleSelect: true,//单选
			pagination:true,
			pageSize:20,
			pageList:[10,20,50,100],
			columns:[[
						{field:'',width:10,checkbox:true},
						{field:'roleName',title:'角色名称',width:80,align:'left'},
						{field:'userCount',title:'下属用户数',width:50},
						{field:'remark',title:'备注',width:300,align:'left'}
			      ]],
			loadFilter:function(data){
				return {
					total: data.page.totalElements,
					rows: data._embedded.roles
				};
			},
			onBeforeLoad:function(param){
				param.page -= 1;
				param.size = param.rows;
				delete param.rows;

			}
		});
		
		$("#datagrid").datagrid('getPager').pagination({   
		    displayMsg:'当前显示从 [{from}] 到 [{to}] 共[{total}]条记录'
		}); 
		
		
			/*权限赋值*/
			var $lromve=$("#lromve");
		 	var $romve=$("#romve");
			var $lromveall=$("#lromveall");
		 	var $romveall=$("#romveall");
		 	
		 	//实现双击不执行单击
			//定义setTimeout执行方法
			var TimeFn = null;
			
			$(".select_role ul").delegate("li" ,"click",function(e) {
				var thisTar = $(this);
				// 取消上次延时未执行的方法
				clearTimeout(TimeFn);
				//执行延时
				TimeFn = setTimeout(function(){
					//do function在此处写单击事件要执行的代码
					thisTar.toggleClass("active");
				},100);
				
			});
			
			/*添加选择*/
			$lromve.click(function(){
				var $opts=$("#lopt li.active");
				$opts.appendTo("#ropt ul");
				$("#ropt li").removeClass("active");
			});

			/*添加全部选择*/
			$lromveall.click(function(){
				var $opts=$("#lopt li");
				$opts.appendTo("#ropt ul");
				$("#ropt li").removeClass("active");
			});
			
			//双击
		 	$("#lopt").delegate("li" ,"dblclick",function(e) {
				// 取消上次延时未执行的方法
				clearTimeout(TimeFn);
				//双击事件的执行代码
				var $opts=$(this);
				$opts.appendTo("#ropt ul");
				$("#ropt li").removeClass("active").children("a").css("color","#000000");
		 	});
			
			
			
			/*删除选择*/
			$romve.click(function(){
		 		var $opts=$("#ropt li.active");
		 		$opts.appendTo("#lopt ul");
				$("#lopt li").removeClass("active");
		 	});

			/*删除全部选择*/
			$romveall.click(function(){
		 		var $opts=$("#ropt li");
		 		$opts.appendTo("#lopt ul");
				$("#lopt li").removeClass("active");
		 	});
			
			//双击
			$("#ropt").delegate("li" ,"dblclick",function(e) {
                // 取消上次延时未执行的方法
				clearTimeout(TimeFn);
				//双击事件的执行代码
				var $opts=$(this);
				$opts.appendTo("#lopt ul");
				$("#lopt li").removeClass("active").children("a").css("color","#000000");
                
            });
		 	

});

	function onSave()
	{
		debugger;
		if($("#authorizeForm").form("validate")){
			$("#instance_save").linkbutton("disable");
			$("#instance_save .l-btn-text").text("提交中...");
			if(modifyOrAddFlag)
			{
				AddRole();
			}
			else
			{
				ModifyRoleInfo();
			}
		}
	    else 
	    {
	    	$(".validatebox-invalid").eq(0).focus();
	    }
	}
	function onAdd()
	{
		$("#roleName").removeAttr("disabled");
		$("#roleName").attr("title","");
		$("#roleName").val("");
		$("#remark").val("");
		if(g_allPermissions.length)
		{
			var loptHtml = createPermissionsHtml(g_allPermissions);
			$("#lopt ul").html(loptHtml);
		}
		else
		{
			getAllPermissions();
		}
		$("#ropt ul").html("");
		$("#authorizeForm").form("validate");
		modifyOrAddFlag = true;
		$("#winEdit").window('setTitle','角色管理-新增');
		$('#winEdit').window('open');
	}

	function update()
	{
		var row = $('#datagrid').datagrid('getSelected');
		if(row == null){
			$.messager.alert('警告',"<p>请选中要修改的记录！</p>","warning");
		}else{
			$("#roleName").val(row.roleName);
			$("#authorizeForm").form("validate");
			if(row.id == "0" || row.id == "1" || 
					row.id == "2" || row.id == "3") {
				$("#roleName").attr("disabled","disabled");
				$("#roleName").attr("title","系统默认角色，不允许重命名");
			}
			else
			{
				$("#roleName").removeAttr("disabled");
				$("#roleName").attr("title","");
			}
			$("#remark").val(row.remark);
			$("#ropt ul").html("");
			if(g_allPermissions.length)
			{
				var loptHtml = createPermissionsHtml(g_allPermissions);
				$("#lopt ul").html(loptHtml);
				getPermissionsByRoleUrl(row._links.permissions.href);
			}
			else
			{
				getAllPermissions(row._links.permissions.href);
			}
			modifyOrAddFlag = false;
			$("#winEdit").window('setTitle','角色管理-修改');
			$('#winEdit').window('open');
		}
	}
	
	function del() {
		var row = $('#datagrid').datagrid('getSelected');
		if(row == null){
			$.messager.alert('警告',"<p>请选中要修改的记录！</p>","warning");
			return;
		}
		
		if(row.id == "0" || row.id == "1" || 
				row.id == "2" || row.id == "3") {
			$.messager.alert('警告',"<p>" + row.roleName + "是系统默认的角色，不允许删除</p>","warning");
			return;
		}
		
		$.messager.confirm('温馨提示','<p>你真的要删除么?</p>',function(result){
			if (result){
				delRole();
			}
		});
	}
	
	function refresh(){
		$('#datagrid').datagrid('reload', BASE_URL_ROLES_CRUD + '?v=' + Date.parse(new Date()));
	}
	
	function rePage() {
		$('#winEdit').window('close');
	}

	function AddRole() {
		var permissions = []; 
		$("#ropt li a").each(function(){ 
			permissions.push($(this).attr("id")); 
		});
		var roleInfoJson = {};
		roleInfoJson["permissionIds"] = permissions;
		roleInfoJson["roleName"] = $("#roleName").val();
		roleInfoJson["remark"] = $("#remark").val();
		$.ajax({
			type: "post",
			url: BASE_URL_ROLES + "/addRole" + '?v=' + Date.parse(new Date()),
			data: JSON.stringify(roleInfoJson),
			contentType: "application/json",
			success: function(result) {
				$("#instance_save").linkbutton("enable");
				$("#instance_save .l-btn-text").text("保存");
				if(result.backValue === true)
				{
					$('#winEdit').window('close');
					$.messager.alert('提示','<p>新增用户角色成功！</p>','info');
					setTimeout(function(){
						$("#datagrid").datagrid("reload", BASE_URL_ROLES_CRUD + '?v=' + Date.parse(new Date()));
					}, 100);
				}
				else
				{
					$.messager.alert('错误','<p>新增用户角色失败！' + result.backValue + '</p>', 'error');
				}
			},
			error: function() {
				$("#instance_save").linkbutton("enable");
				$("#instance_save .l-btn-text").text("保存");
				$.messager.alert('错误','<p>服务异常，新增用户角色失败，请稍后重试！</p>', 'error');
			}
		});
	}

	function ModifyRoleInfo() {
		var row = $('#datagrid').datagrid('getSelected');
		
		if(row.id == "0" || row.id == "1" || 
				row.id == "2" || row.id == "3") {
			if(row.roleName != $("#roleName").val())
			{
				$("#instance_save").linkbutton("enable");
				$("#instance_save .l-btn-text").text("保存");
				$.messager.alert('警告',"<p>" + row.roleName + "是系统默认角色，不允许重命名</p>","warning");
				return;
			}
		}
		
		var permissions = []; 
		$("#ropt li a").each(function(){ 
			permissions.push($(this).attr("id")); 
		});
		var roleInfoJson = {};
		roleInfoJson["id"] = row.id;
		roleInfoJson["permissionIds"] = permissions;
		roleInfoJson["roleName"] = $("#roleName").val();
		roleInfoJson["remark"] = $("#remark").val();
		$.ajax({
			type: "post",
			url: BASE_URL_ROLES + "/updateRole" + '?v=' + Date.parse(new Date()),
			data: JSON.stringify(roleInfoJson),
			contentType: "application/json",
			success: function(result) {
				$("#instance_save").linkbutton("enable");
				$("#instance_save .l-btn-text").text("保存");
				if(result.backValue === true)
				{
					$('#winEdit').window('close');
					$.messager.alert('提示','<p>修改用户角色成功！</p>','info');
					setTimeout(function(){
						$("#datagrid").datagrid("reload", BASE_URL_ROLES_CRUD + '?v=' + Date.parse(new Date()));
					}, 100);
				}
				else
				{
					$.messager.alert('错误','<p>修改用户角色失败！' + result.backValue + '</p>', 'error');
				}
			},
			error: function() {
				$("#instance_save").linkbutton("enable");
				$("#instance_save .l-btn-text").text("保存");
				$.messager.alert('错误','<p>服务异常，修改用户角色失败，请稍后重试！</p>', 'error');
			}
		});
	}
	
	function delRole() {
		var row = $('#datagrid').datagrid('getSelected');
		var roleInfoJson = {};
		roleInfoJson["id"] = row.id;
		$.ajax({
			url: BASE_URL_ROLES_CRUD + '/deleteRole?v=' + Date.parse(new Date()),
			dataType:'json',
			type:'delete',
			data: JSON.stringify(roleInfoJson),
			async:false,
			contentType:"application/json",
			timeout:30000,
			success:function(result){
				if(result.backValue === true)
				{
					$.messager.alert('提示',"<p>删除用户角色成功！</p>","info");
					//$('#datagrid').datagrid('deleteRow',$('#datagrid').datagrid('getRowIndex', row));
					$("#datagrid").datagrid("reload", BASE_URL_ROLES_CRUD + '?v=' + Date.parse(new Date()));
				}
				else
				{
					$.messager.alert('错误',"<p>删除用户角色失败！" + result.backValue + "</p>","error");
				}
			},
			error:function(xhr,s,err){
				$.messager.alert('错误',"<p>服务异常，删除用户角色失败！</p>","error");
			}
 		});
	}
	
	function getAllPermissions(rolePermissionUrl) {
		$.ajax({
			type: "get",
			url: BASE_URL_API + "/permissions" + '?v=' + Date.parse(new Date()),
			data: "",
			contentType: "application/json",
			success: function(result) {
				g_allPermissions = result._embedded.permissions;
				var loptHtml = createPermissionsHtml(g_allPermissions);
				$("#lopt ul").html(loptHtml);
				if(rolePermissionUrl)
				{
					getPermissionsByRoleUrl(rolePermissionUrl);
				}
			},
			error: function() {
				$.messager.alert('错误','<p>服务异常，获取角色权限列表失败，请稍后重试！</p>', 'error');
			}
		});
	}

	function getPermissionsByRoleUrl(rolePermissionUrl) {
		$.ajax({
			type: "get",
			url: rolePermissionUrl,
			data: "",
			contentType: "application/json",
			success: function(result) {
				if(result && result._embedded && result._embedded.permissions)
				{
					for(var i = 0, len = result._embedded.permissions.length; i < len; ++i)
					{
						$("#" + result._embedded.permissions[i].id, $("#lopt")).dblclick();
					}
				}
			},
			error: function() {
				$.messager.alert('错误','<p>服务异常，获取角色权限列表失败，请稍后重试！</p>', 'error');
			}
		});
	}
	
	function createPermissionsHtml(permissionsList) {
		if(!permissionsList)
		{
			return "";
		}
		var permissionsNum = permissionsList.length;
		var liItemHtml = "";
		for(var i = 0; i < permissionsNum; ++i)
		{
			liItemHtml += '<li><img src="../../images/st_folder.png" alt="' + permissionsList[i].priName + '" /><a href="javascript:void(0);" id="' + permissionsList[i].id + '">' + 
			permissionsList[i].priName + '</a></li>';
		}
		return liItemHtml;
		
	}

</script>
</body>
</html>



